const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const multer = require('multer');
const jwt = require('jsonwebtoken');
const cors = require('cors');

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

app.use(cors());
app.use(express.json());
app.use('/uploads', express.static('uploads'));

// 文件上传配置
const storage = multer.diskStorage({
  destination: 'uploads/',
  filename: function (req, file, cb) {
    cb(null, Date.now() + '-' + file.originalname);
  }
});

const upload = multer({ storage: storage });

// 用户存储（实际应用中应该使用数据库）
const users = new Map();
const JWT_SECRET = 'your-secret-key';

// 认证中间件
const authenticateToken = (req, res, next) => {
  const token = req.headers['authorization']?.split(' ')[1];
  if (!token) return res.sendStatus(401);

  jwt.verify(token, JWT_SECRET, (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
  });
};

// 登录接口
app.post('/api/login', (req, res) => {
  const { username, password } = req.body;
  // 简单的验证逻辑，实际应用中需要更安全的处理
  if (password === 'password') {
    const token = jwt.sign({ username }, JWT_SECRET);
    res.json({ token });
  } else {
    res.status(401).json({ message: '用户名或密码错误' });
  }
});

// 图片上传接口
app.post('/api/upload', authenticateToken, upload.single('image'), (req, res) => {
  res.json({ url: `/uploads/${req.file.filename}` });
});

// WebSocket连接处理
wss.on('connection', (ws, req) => {
  console.log('WebSocket 连接已建立!!!!')
  let user = null;

  ws.on('message', (message) => {
    const data = JSON.parse(message);
    console.log('收到消息:', data)
    switch (data.type) {
      case 'auth':
        try {
          const decoded = jwt.verify(data.token, JWT_SECRET);
          user = decoded.username;
          
          // 检查用户是否已经在线
          const existingUser = users.get(user);
          if (existingUser) {
            // 如果用户已经在线，更新其 WebSocket 连接
            existingUser.ws = ws;
          } else {
            // 新用户上线
            users.set(user, { 
              ws,
              online: true,
              lastActive: new Date()
            });
          }
          
          // 广播更新后的用户状态
          broadcastUserStatus();
        } catch (err) {
          ws.close();
        }
        break;
      
      case 'message':
        if (user) {
          broadcast({
            type: 'message',
            content: data.content,
            contentType: data.contentType,
            from: user,
            timestamp: new Date()
          });
        }
        break;
    }
  });

  ws.on('close', () => {
    if (user) {
      users.delete(user);
      broadcastUserStatus();
    }
  });
});

function broadcast(message) {
  wss.clients.forEach(client => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(JSON.stringify(message));
    }
  });
}

function broadcastUserStatus() {
  // 从 users Map 构建完整的用户状态列表
  const userStatusList = Array.from(users.entries()).map(([username, data]) => ({
    username,
    online: true,
    lastActive: new Date().toISOString(),
    // 可以添加更多用户状态信息
  }));
  
  // 广播用户状态
  broadcast({
    type: 'userStatus',
    users: userStatusList,
    timestamp: new Date().toISOString()
  });
}

server.listen(3000, () => {
  console.log('Server running on port 3000');
});